<template>
  <div class="review-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>内容审核</span>
          <div class="filter-box">
            <el-select v-model="contentType" placeholder="内容类型" @change="handleFilterChange">
              <el-option label="全部" value="all" />
              <el-option label="帖子" value="post" />
              <el-option label="评论" value="comment" />
            </el-select>
          </div>
        </div>
      </template>

      <!-- 待审核内容列表 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="待审核" name="pending">
          <div v-if="activeTab === 'pending'">
            <el-empty v-if="pendingList.length === 0" description="暂无待审核内容" />
            <div v-else class="content-list">
              <el-table
                :data="pendingList"
                style="width: 100%"
                v-loading="loading"
                border
                class="compact-table"
                size="small"
                :cell-class-name="tableCellClassName"
                row-class-name="compact-row"
              >
                <el-table-column prop="id" label="ID" width="60" />
                <el-table-column prop="type" label="类型" width="80">
                  <template #default="scope">
                    <el-tag :type="scope.row.type === 'post' ? 'primary' : 'success'" effect="plain" class="status-tag" size="small">
                      {{ scope.row.type === 'post' ? '帖子' : '评论' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="title" label="标题/内容" min-width="180">
                  <template #default="scope">
                    <div class="post-content">
                      <div class="post-text">
                        <el-tooltip :content="scope.row.type === 'post' ? (scope.row.title || '') : scope.row.content" placement="top" :show-after="1000">
                          <span class="truncate-text">{{ scope.row.type === 'post' ? (scope.row.title || '') : scope.row.content }}</span>
                        </el-tooltip>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="author" label="作者" width="100" />
                <el-table-column prop="createTime" label="提交时间" width="120">
                  <template #default="scope">
                    <div class="time-cell">
                      <el-icon><Clock /></el-icon>
                      <span>{{ scope.row.createTime }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="160">
                  <template #default="scope">
                    <div class="action-btn-group">
                      <el-button 
                        type="success" 
                        size="small" 
                        @click="approveContent(scope.row)"
                      >
                        通过
                      </el-button>
                      <el-button 
                        type="danger" 
                        size="small" 
                        @click="rejectContent(scope.row)"
                      >
                        驳回
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 分页器 -->
            <div class="pagination-container" v-if="pendingList.length > 0">
              <el-pagination
                v-model:current-page="pendingCurrentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 50]"
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="pendingTotal"
                @size-change="handleSizeChange"
                @current-change="(val) => handleCurrentChange(val, 'pending')"
              />
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="已审核" name="reviewed">
          <div v-if="activeTab === 'reviewed'">
            <el-table
              :data="reviewedList"
              style="width: 100%"
              v-loading="loading"
              border
              class="compact-table"
              size="small"
              :cell-class-name="tableCellClassName"
              row-class-name="compact-row"
            >
              <el-table-column prop="id" label="ID" width="60" />
              <el-table-column prop="type" label="类型" width="80">
                <template #default="scope">
                  <el-tag :type="scope.row.type === 'post' ? 'primary' : 'success'" effect="plain" class="status-tag" size="small">
                    {{ scope.row.type === 'post' ? '帖子' : '评论' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="title" label="标题/内容" min-width="180">
                <template #default="scope">
                  <div class="post-content">
                    <div class="post-text">
                      <el-tooltip :content="scope.row.type === 'post' ? scope.row.title : scope.row.content" placement="top" :show-after="1000">
                        <span class="truncate-text">{{ scope.row.type === 'post' ? scope.row.title : scope.row.content }}</span>
                      </el-tooltip>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="author" label="作者" width="100" />
              <el-table-column prop="createTime" label="提交时间" width="120">
                <template #default="scope">
                  <div class="time-cell">
                    <el-icon><Clock /></el-icon>
                    <span>{{ scope.row.createTime }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="reviewTime" label="审核时间" width="120">
                <template #default="scope">
                  <div class="time-cell">
                    <el-icon><Clock /></el-icon>
                    <span>{{ scope.row.reviewTime }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="reviewResult" label="审核结果" width="80">
                <template #default="scope">
                  <div class="status-container">
                    <el-tag :type="scope.row.reviewResult === '通过' ? 'success' : 'danger'" class="status-tag" size="small">
                      {{ scope.row.reviewResult }}
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="reviewer" label="审核人" width="100" />
            </el-table>
            <!-- 分页器 -->
            <div class="pagination-container" v-if="reviewedList.length > 0">
              <el-pagination
                v-model:current-page="reviewedCurrentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="reviewedTotal"
                @size-change="handleSizeChange"
                @current-change="(val) => handleCurrentChange(val, 'reviewed')"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 驳回理由对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="驳回理由" width="30%">
      <el-form :model="rejectForm">
        <el-form-item label="驳回原因" required>
          <el-input v-model="rejectForm.reason" type="textarea" rows="3" placeholder="请输入驳回原因"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmReject">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Clock } from '@element-plus/icons-vue'

// 标签页和筛选
const activeTab = ref('pending')
const contentType = ref('all')

// 表格数据
const loading = ref(false)
const pendingList = ref([])
const reviewedList = ref([])
const pendingTotal = ref(0)
const reviewedTotal = ref(0)
const pendingCurrentPage = ref(1)
const reviewedCurrentPage = ref(1)
const pageSize = ref(10)

// 驳回对话框
const rejectDialogVisible = ref(false)
const rejectForm = reactive({
  reason: ''
})
const currentItem = ref(null)

// 切换标签页
const handleTabClick = (tab) => {
  if (tab.props.name === 'pending') {
    loadPendingContent()
  } else {
    loadReviewedContent()
  }
}

// 处理筛选变化
const handleFilterChange = () => {
  if (activeTab.value === 'pending') {
    pendingCurrentPage.value = 1
    loadPendingContent()
  } else {
    reviewedCurrentPage.value = 1
    loadReviewedContent()
  }
}

// 加载待审核内容
const loadPendingContent = async () => {
  loading.value = true
  try {
    // 模拟异步请求
    setTimeout(() => {
      // 这里应该是实际的API调用
      // const response = await fetch(`/api/admin/review/pending?page=${pendingCurrentPage.value}&pageSize=${pageSize.value}&type=${contentType.value}`)
      // const data = await response.json()
      // pendingList.value = data.list
      // pendingTotal.value = data.total
      //
      // 模拟数据
      const mockData = []
      //
      // 生成5-10条随机数据
      const count = Math.floor(Math.random() * 6) + 5
      //
      for (let i = 1; i <= count; i++) {
        const id = (pendingCurrentPage.value - 1) * pageSize.value + i
        const type = contentType.value === 'all'
          ? (Math.random() > 0.5 ? 'post' : 'comment')
          : contentType.value
        //
        if (type === 'post') {
          mockData.push({
            id,
            type: 'post',
            title: `待审核帖子标题 ${id}`,
            content: `<p>这是一篇待审核的帖子内容，ID为 ${id}。</p><p>这里是帖子的详细内容，可能包含一些需要审核的文字、图片等。</p>`,
            author: `用户${Math.floor(Math.random() * 100)}`,
            createTime: new Date().toLocaleDateString(),
          })
        } else {
          mockData.push({
            id,
            type: 'comment',
            content: `这是一条待审核的评论，ID为 ${id}。评论内容可能包含一些需要审核的文字。`,
            postId: Math.floor(Math.random() * 100) + 1,
            postTitle: `帖子标题 ${Math.floor(Math.random() * 100) + 1}`,
            author: `用户${Math.floor(Math.random() * 100)}`,
            createTime: new Date().toLocaleDateString(),
          })
        }
      }
      //
      pendingList.value = mockData
      pendingTotal.value = 25 // 假设总数为25
      //
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('加载待审核内容失败:', error)
    loading.value = false
  }
}

// 加载已审核内容
const loadReviewedContent = async () => {
  loading.value = true
  try {
    // 模拟异步请求
    setTimeout(() => {
      // 这里应该是实际的API调用
      // const response = await fetch(`/api/admin/review/reviewed?page=${reviewedCurrentPage.value}&pageSize=${pageSize.value}&type=${contentType.value}`)
      // const data = await response.json()
      // reviewedList.value = data.list
      // reviewedTotal.value = data.total
      //
      // 模拟数据
      const mockData = []
      const reviewResults = ['通过', '驳回']
      //
      for (let i = 1; i <= pageSize.value; i++) {
        const id = (reviewedCurrentPage.value - 1) * pageSize.value + i
        const type = contentType.value === 'all'
          ? (Math.random() > 0.5 ? 'post' : 'comment')
          : contentType.value
        const reviewResult = reviewResults[Math.floor(Math.random() * reviewResults.length)]
        //
        mockData.push({
          id,
          type,
          title: type === 'post' ? `帖子标题 ${id}` : '',
          content: type === 'post'
            ? `<p>这是一篇帖子内容，ID为 ${id}。</p>`
            : `这是一条评论，ID为 ${id}。`,
          author: `用户${Math.floor(Math.random() * 100)}`,
          createTime: new Date(Date.now() - Math.floor(Math.random() * 7) * 24 * 3600 * 1000).toLocaleDateString(),
          reviewTime: new Date().toLocaleDateString(),
          reviewResult,
          reviewer: '管理员'
        })
      }
      //
      reviewedList.value = mockData
      reviewedTotal.value = 100 // 假设总数为100
      //
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('加载已审核内容失败:', error)
    loading.value = false
  }
}

// 首次加载
onMounted(() => {
  loadPendingContent()
})

// 处理页码变化
const handleCurrentChange = (val, type) => {
  if (type === 'pending') {
    pendingCurrentPage.value = val
    loadPendingContent()
  } else {
    reviewedCurrentPage.value = val
    loadReviewedContent()
  }
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  pendingCurrentPage.value = 1
  reviewedCurrentPage.value = 1
  //
  if (activeTab.value === 'pending') {
    loadPendingContent()
  } else {
    loadReviewedContent()
  }
}

// 通过内容
const approveContent = async (item) => {
  try {
    // 确认操作
    await ElMessageBox.confirm(`确定要通过这${item.type === 'post' ? '篇帖子' : '条评论'}吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    //
    // 模拟API调用
    // await fetch(`/api/admin/review/${item.id}/approve`, {
    //   method: 'PUT',
    //   headers: {
    //     'Content-Type': 'application/json'
    //   },
    //   body: JSON.stringify({
    //     type: item.type
    //   })
    // })
    //
    // 从待审核列表中移除
    pendingList.value = pendingList.value.filter(i => i.id !== item.id)
    pendingTotal.value--
    //
    ElMessage.success('审核通过成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核操作失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

// 驳回内容
const rejectContent = (item) => {
  currentItem.value = item
  rejectForm.reason = ''
  rejectDialogVisible.value = true
}

// 确认驳回
const confirmReject = async () => {
  if (!rejectForm.reason.trim()) {
    ElMessage.warning('请输入驳回原因')
    return
  }
  //
  try {
    // 模拟API调用
    // await fetch(`/api/admin/review/${currentItem.value.id}/reject`, {
    //   method: 'PUT',
    //   headers: {
    //     'Content-Type': 'application/json'
    //   },
    //   body: JSON.stringify({
    //     type: currentItem.value.type,
    //     reason: rejectForm.reason
    //   })
    // })
    //
    // 从待审核列表中移除
    pendingList.value = pendingList.value.filter(item => item.id !== currentItem.value.id)
    pendingTotal.value--
    //
    ElMessage.success('已驳回')
    rejectDialogVisible.value = false
  } catch (error) {
    console.error('驳回操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 设置表格单元格class
const tableCellClassName = () => {
  return 'compact-cell'
}
</script>

<style scoped>
.review-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-box {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.content-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.content-item {
  margin-bottom: 10px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.content-meta {
  display: flex;
  gap: 15px;
  color: #909399;
  font-size: 14px;
}

.post-content, .comment-content {
  margin-bottom: 15px;
  line-height: 1.6;
}

.post-content h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.content-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.truncate-text {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
  font-size: 12px;
}

.compact-table {
  /* Add your styles for the compact table here */
}

.compact-row {
  /* Add your styles for the compact row here */
}

.compact-cell {
  /* Add your styles for the compact cell here */
}

.time-cell {
  display: flex;
  align-items: center;
}

.status-container {
  display: flex;
  justify-content: center;
}

.status-tag {
  /* Add your styles for the status tag here */
}

/* 表头居中 */
:deep(.el-table th) {
  text-align: center;
}
</style> 